package io.renren.handler;

import io.renren.builder.TextBuilder;
import io.renren.entity.*;
import io.renren.entity.Dictionary;
import io.renren.service.*;
import io.renren.utils.ConfigConstant;
import io.renren.utils.VoiceSearchUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class MsgHandler extends AbstractHandler {

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private BookVideoService bookVideoService;

    @Autowired
    private UserDefaultInfoService userDefaultInfoService;

    @Autowired
    private BookService bookService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context,
                                    WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        //TODO 组装回复消息
        String content = "未查询到相应的内容，请点击相应菜单浏览更多内容或重新搜索。";
        String errContent = "未查询到相应的内容，请点击相应菜单浏览更多内容，或重新搜索，例如数学第五页。";
        String key = wxMessage.getContent();
        if (wxMessage.getRecognition() != null) {
            key = wxMessage.getRecognition();
        }

        log.info("用户发送内容：{}", key);

        if (key == null) {
            return null;
        }

        //根据年级和科目查询列表信息
        List<Dictionary> dictionaryList = dictionaryService.queryList(null);
        dictionaryList = dictionaryList.stream()
                .filter(dictionary -> dictionary.getType().equals("T02") && "1".equals(dictionary.getStatus()) && "0".equals(dictionary.getDeleted()))
                .collect(Collectors.toList());
        String[] subjectAndPageNo = VoiceSearchUtil.SubjectAndPageNoParse(key, dictionaryList);
        if (subjectAndPageNo[0].length() == 0 || subjectAndPageNo[1].length() == 0) {
            return new TextBuilder().build(errContent, wxMessage, weixinService);
        }

        //获取wxUser对象
        WxUser wxUser = new WxUser();
        Map userQuery = new HashMap();
        userQuery.put("openId", wxMessage.getFromUser());
        List<WxUser> wxUserList = wxUserService.queryList(userQuery);
        if (wxUserList != null && wxUserList.size() > 0) {
            wxUser = wxUserList.get(0);
        } else {
            try {
                WxMpUser mpUser = weixinService.getUserService().userInfo(wxMessage.getFromUser());
                wxUser.setStatus("0");
                wxUser.setSubscribe("1");
                wxUser.setCreateTime(new Date());
                wxUser.setSubscribeTime(new Date());
                wxUser.setUnionId(mpUser.getUnionId());
                wxUser.setOpenId(wxMessage.getFromUser());
                wxUser.setImgUrl(mpUser.getHeadImgUrl());
                wxUser.setNickName(mpUser.getNickname());
                wxUser.setSubscribeScene(mpUser.getSubscribeScene());
                wxUser.setQrSceneStr("0".equals(mpUser.getQrScene())?mpUser.getQrSceneStr(): mpUser.getQrScene());

                wxUserService.save(wxUser);
            } catch (WxErrorException e) {
                e.printStackTrace();
                return new TextBuilder().build("出现异常，请联系管理员处理", wxMessage, weixinService);
            }

        }

        //查询用户默认信息
        Map query = new HashMap();
        query.put("userId", wxUser.getId());
        query.put("subjectId", subjectAndPageNo[0]);
        query.put("gradeId", wxUser.getGradeId() == null ? ConfigConstant.DEFAULT_GRADE_ID : wxUser.getGradeId());
        List<UserDefaultInfo> userDefaultInfoList = userDefaultInfoService.queryList(query);

        //如果有记录则使用默认教版，如果没有就不适用
        if (userDefaultInfoList != null && userDefaultInfoList.size() > 0) {
            query.put("versionId", userDefaultInfoList.get(0).getVersionId());
        }

        List<Book> bookList = bookService.queryList(query);
        if (bookList == null || bookList.size() == 0) {
            return new TextBuilder().build(content, wxMessage, weixinService);
        }

        Stream<List<BookVideo>> listStream = bookList.stream()
                .filter(book -> book.getStatus().equals("1") && book.getDeleted().equals("0"))
                .map(book -> {
                            Map videoQuery = new HashMap();
                            videoQuery.put("status", "1");
                            videoQuery.put("deleted", "0");
                            videoQuery.put("bookId", book.getId());
                            videoQuery.put("pageNo", subjectAndPageNo[1]);
                            List<BookVideo> bookVideoList = bookVideoService.queryList(videoQuery);
                            return bookVideoList;
                        }
                );

        List<BookVideo> videoList = listStream.reduce(new ArrayList<>(), (bookVideoList, bookVideoList1) -> {
                    bookVideoList.addAll(bookVideoList1);
                    return bookVideoList;
                }
        );
        if (videoList == null || videoList.size() == 0) {
            return new TextBuilder().build(content, wxMessage, weixinService);
        }

        List<WxMpXmlOutNewsMessage.Item> collect = videoList.stream()
                .filter(bookVideo -> "0".equals(bookVideo.getBook().getDeleted()) && "1".equals(bookVideo.getBook().getStatus()))
                .limit(8)
                .sorted(Comparator.comparing(BookVideo::getPageNo).thenComparing(BookVideo::getOrderField))
                .map(bookVideo -> {
                    WxMpXmlOutNewsMessage.Item item = new WxMpXmlOutNewsMessage.Item();
                    item.setDescription("立即点击查看内容");
                    item.setTitle(bookVideo.getVideoName());
                    item.setUrl(ConfigConstant.BASE_URL + "/api/video_detail.html?videoId=" + bookVideo.getId() + "&userFrom=2");
                    item.setPicUrl(StringUtils.isEmpty(bookVideo.getBook().getCoverUrl()) ? ConfigConstant.DEFAULT_BOOK_COVER : bookVideo.getBook().getCoverUrl());
                    return item;
                })
                .collect(Collectors.toList());
        WxMpXmlOutNewsMessage.Item[] items = new WxMpXmlOutNewsMessage.Item[collect.size()];

        WxMpXmlOutNewsMessage newsMessage = WxMpXmlOutMessage.NEWS()
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .addArticle(collect.toArray(items))
                .build();

        return newsMessage;
    }

}
